package cn.user.domain.dao;

import java.util.ArrayList;
import java.util.List;

import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import cn.user.domain.Detialed;
import cn.user.domain.Favorite;
import webServlet.detialServlet;

public class DetialDao {
	private JdbcTemplate jdbctemplate = new JdbcTemplate(Druid0.getDataSource());

	public List<Detialed> findAll(int foodid) {
		String sql = "select * from detialed where foodid = ? ";
		return jdbctemplate.query(sql, new BeanPropertyRowMapper<Detialed>(Detialed.class), foodid);
	}
	
	public Detialed findByfoodid (int foodid) {
		try{
			String sql = "select * from detialed where foodid = ? ";
			Detialed food = jdbctemplate.queryForObject(sql, new BeanPropertyRowMapper<Detialed>(Detialed.class),foodid);
			return food;
			}
			catch(DataAccessException e) {
				//e.printStackTrace();
				return null;
			}
	}
	
	public void add(Detialed de) {
		String sql = "INSERT INTO detialed VALUES(?,?,?,?,?,?,?,?,?,?)";
		jdbctemplate.update(sql, de.getFoodid(),de.getDname(),de.getDetial(),de.getBuyurl(),de.getHirstory(),
				de.getCharactor(),de.getDomake(),de.getImg1(),de.getImg2(),de.getImg3());
	}
	
	public int count(String keyword) {
		String sql = " SELECT COUNT(*) FROM detialed WHERE dname LIKE ? OR  detial LIKE ? ";
		String a = "%"+keyword+"%";
		return jdbctemplate.queryForObject(sql, Integer.class,a,a);
	}
	
	public List<Detialed> findbySearch(String foodinf,int start) {
		 String sql = " select * from detialed where 1 = 1 and limit ? , ?";
		 StringBuilder sb = new StringBuilder(sql);
		 if(foodinf==null) {
			 return jdbctemplate.query(sql, new BeanPropertyRowMapper<Detialed>(Detialed.class),start,4);
		 }
		 sql = " select * from detialed where 1 = 1  and dname like ? or detial like ?  limit ? , ?";
		 return jdbctemplate.query(sql, new BeanPropertyRowMapper<Detialed>(Detialed.class),"%"+foodinf+"%","%"+foodinf+"%",start*4,4);
	}
}
